package io.virtualapp.splash;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import org.litepal.crud.DataSupport;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.VCommends;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.Ads;
import io.virtualapp.bean.Contract;
import io.virtualapp.bean.Gds;
import io.virtualapp.bean.ResultBean;
import io.virtualapp.bean.Swt;
import io.virtualapp.bean.UpdateBean;
import io.virtualapp.bean.Vip;
import io.virtualapp.home.IndexMainActivity;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.http.HttpUtils;
import io.virtualapp.mylibrary.util.GlideLoadUtils;
import io.virtualapp.mylibrary.util.PermissionUtils;
import io.virtualapp.mylibrary.util.SpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import io.virtualapp.mylibrary.util.Utils;
import io.virtualapp.widgets.CenterDialog;
import io.virtualapp.widgets.OnDialogClickListener;
import jonathanfinerty.once.Once;
import okhttp3.Request;
import okhttp3.Response;
public class SplashActivity extends VActivity {
    @BindView(R.id.splash_img)
    ImageView splashImg;
    @BindView(R.id.splash_btn)
    Button splashBtn;
    private boolean isReg; //是否注册
    private Handler mHander = new Handler();
    private int RESULT_ACTION_USAGE_ACCESS_SETTINGS = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        @SuppressWarnings("unused") boolean enterGuide = !Once.beenDone(Once.THIS_APP_INSTALL, VCommends.TAG_NEW_VERSION);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        isReg = SpUtils.getInstance().getBoolean( VCommends.LOCK_IS_REG, true );//是否是第一次注册
        initDatas();
    }
    protected void initDatas() {
        if (Utils.isNetworkAvailable( SplashActivity.this )) { //如果有网请求权限
            if (isReg){
                PermissionUtils.checkAndRequestPermission( SplashActivity.this, Manifest.permission.READ_PHONE_STATE, 1, new PermissionUtils.PermissionRequestSuccessCallBack() {
                    @Override
                    public void onHasPermission() {
                        regDevice();
                    }
                } );
            }else {
                getUpdate();
            }
        } else {
            if (!isReg){
                new Handler().postDelayed(() -> {
                    IndexMainActivity.goHome(this);
                    finish();
                }, 2000L);
                overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
            }else {
                ToastUtils.showShortToast("网络异常！请开启网络后重新打开");
            }
         }

    }
    /**
     * 注册设备
     */
    private void regDevice() {
        if (isReg) {
              HttpUtils.getInstance().postRegister(new BaseCallback<ResultBean>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {
                    Log.e( "TAG", "注册失败" );
                    SpUtils.getInstance().putBoolean( VCommends.LOCK_IS_REG, true );
                }

                @Override
                public void onSuccess(Response response, ResultBean resultBean) {
                    SpUtils.getInstance().putBoolean( VCommends.LOCK_IS_REG, false );

                    if (resultBean.isIssucc()) {
                        Log.e( "TAG", "注册成功！" + resultBean.isIssucc() );
                        getUpdate();
                    }else {
                        Log.e( "TAG", "注册成功！" + resultBean.isIssucc() );
                    }

                }


                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    Log.e( "TAG", "注册失败" + e.toString() );
                }
            } );

        } else {
            getUpdate();

        }
    }
    private void getUpdate() {
          HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(Response response, UpdateBean o) {
                Log.e("TAG",o.toString());
                /**
                 *      把所有数据全部存入本地数据库
                 */
                if (o != null && response.isSuccessful()) {
                    if (DataSupport.findFirst( UpdateBean.class ) != null) {
                        DataSupport.deleteAll( UpdateBean.class );
                    }
                    o.save();
                    List<Ads> ads = o.getAds();
                    if (DataSupport.findAll( Ads.class ).size() > 0 && DataSupport.findAll( Ads.class ) != null) {
                        DataSupport.deleteAll( Ads.class );
                    }
                    if (ads != null)
                        for (int i = 0; i < ads.size(); i++) {
                            Ads ads1 = ads.get( i );
                            Log.e( "TAG",ads1.getPos()+"getPos" );
                            if (ads1.getPos().equals( "1260" )) {
                                GlideLoadUtils.getInstance().glideLoad( SplashActivity.this,ads1.getImg(),splashImg, R.mipmap.splash );
                                splashImg.setOnClickListener(v -> openActionView(ads1.getLink()));
                            }
                            ads1.save();
                        }

                    List<Gds> gds = o.getGds();
                    if (DataSupport.findAll( Gds.class ).size() > 0 && DataSupport.findAll( Gds.class ) != null) {
                        DataSupport.deleteAll( Gds.class );
                    }
                    for (int i = 0; i < gds.size(); i++) {
                        Gds gds1 = gds.get( i );
                        if (i == 0) {
                            gds1.setSelect( true );
                        } else {
                            gds1.setSelect( false );
                        }
                        gds1.save();
                    }

                    List<Swt> swt = o.getSwt();
                    if (DataSupport.findAll( Swt.class ).size() > 0 && DataSupport.findAll( Swt.class ) != null) {
                        DataSupport.deleteAll( Swt.class );
                    }
                    for (int i = 0; i < swt.size(); i++) {
                        Swt swt1 = swt.get( i );
                        swt1.save();
                    }

                    Contract contract = o.getContract();
                    if (DataSupport.findFirst( Contract.class ) != null) {
                        DataSupport.deleteAll( Contract.class );
                    }
                    contract.save();

                    Vip vip = o.getVip();
                    if (DataSupport.findFirst( Vip.class ) != null) {
                        DataSupport.deleteAll( Vip.class );
                    }
                    vip.save();

                }
                List<Swt> swts = DataSupport.findAll(Swt.class);    //8.0开关
                if (swts.size() > 0) {
                    for (int i = 0; i < swts.size(); i++) {
                        if (swts.get(i).getCode().equals("S0280219")) {
                              if (Build.VERSION.SDK_INT>=27 && swts.get(i).getVal1()==1){
                                  cantUseFor8();
                                  return;
                              }

                        }
                    }
                }
                new Handler().postDelayed(() -> {
                    IndexMainActivity.goHome(SplashActivity.this);
                    finish();
                }, 2000L);

                overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );


            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        } );
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        if (requestCode==RESULT_ACTION_USAGE_ACCESS_SETTINGS)
            PermissionUtils.onRequestPermissionResult( SplashActivity.this, Manifest.permission.READ_PHONE_STATE, grantResults, new PermissionUtils.PermissionCheckCallBack() {
                @Override
                public void onHasPermission() {
                    regDevice();


                }

                @Override
                public void onUserHasAlreadyTurnedDown(String... permission) {
                    ShowTipDialog("温馨提示",
                            "授予权限能使数据绑定手机哦，点击确定继续授权",
                            "确定", new OnDialogClickListener() {
                                @Override
                                public void OnDialogOK() {
                                    PermissionUtils.requestPermission(SplashActivity.this,
                                            Manifest.permission.READ_PHONE_STATE,
                                            1);
                                }

                                @Override
                                public void OnDialogExit() {
                                    regDevice();
                                }
                            });
                }

                @Override
                public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                   regDevice();
                }
            } );
    }
    public void ShowTipDialog(String name, String tipcontent, String buttonoktext, OnDialogClickListener listener) {
        int[] intids = new int[]{
                R.id.dialog_bt_dis,
                R.id.dialog_bt_ok
        };
        CenterDialog dialog = new CenterDialog(SplashActivity.this, R.layout.dialog_tip_2_bt_layout, intids);
        dialog.setOnCenterClickListener((dial, view) -> {
            if (view.getId() == R.id.dialog_bt_ok) {
                listener.OnDialogOK();
                dialog.dismiss();
            }
            if (view.getId() == R.id.dialog_bt_dis) {
                dialog.dismiss();
                listener.OnDialogExit();
            }
        });
        dialog.show();
        dialog.setText(R.id.dialog_tv_title, name);
        dialog.setText(R.id.dialog_tv_text, tipcontent);
        dialog.setText(R.id.dialog_bt_ok, buttonoktext);
    }

    /**
     * 8.0不能使用弹窗
     */
    private void cantUseFor8(){
        AlertDialog.Builder builder=new AlertDialog.Builder(SplashActivity.this);
        builder.setCancelable(false);
        builder.setTitle("温馨提示");
        builder.setMessage("很抱歉，当前软件在8.0系统功能暂未可用，正在更新中");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.show();
    }
}
